const express = require('express');
const cors = require('cors');
const path = require('path');
const { SERVER_CONFIG, PATH_CONFIG } = require('./config/constants');
const { initializeDirectories } = require('./utils/fileUtils');
const QueueManager = require('./services/queueManager');
const routes = require('./routes');
const { initFFmpeg } = require('./utils/ffmpegInit');
const videoRoutes = require('./routes/videoRoutes');
const { ensureDirectoryExists } = require('./utils/fileUtils');

// 创建Express应用
const app = express();

// 启用 CORS
app.use(cors());
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

// 初始化应用
async function startServer() {
    try {
        // 初始化 FFmpeg
        console.log('\n=== 初始化 FFmpeg ===');
        const ffmpegInitialized = await initFFmpeg();
        if (!ffmpegInitialized) {
            throw new Error('FFmpeg 初始化失败');
        }
        console.log('=== FFmpeg 初始化完成 ===\n');

        // 初始化目录
        console.log('=== 初始化目录 ===');
        ensureDirectoryExists(PATH_CONFIG.uploadDir);
        ensureDirectoryExists(PATH_CONFIG.outputDir);
        ensureDirectoryExists(PATH_CONFIG.logsDir);
        console.log('✨ 所有目录初始化完成\n');

        // 初始化队列管理器
        app.locals.queueManager = new QueueManager();

        // 配置路由
        app.use('/api/video', videoRoutes);

        // 错误处理中间件
        app.use((err, req, res, next) => {
            console.error('应用错误:', err);
            res.status(500).json({ error: err.message || '服务器内部错误' });
        });

        // 启动服务器
        app.listen(SERVER_CONFIG.port, () => {
            console.log(`\n=== 服务器信息 ===`);
            console.log(`服务器运行在 http://localhost:${SERVER_CONFIG.port}`);
            console.log(`上传目录: ${PATH_CONFIG.uploadDir}`);
            console.log(`输出目录: ${PATH_CONFIG.outputDir}`);
            console.log(`日志目录: ${PATH_CONFIG.logsDir}`);
            console.log(`最大并发任务数: ${SERVER_CONFIG.maxConcurrentJobs}`);
            console.log('==================\n');
        });
    } catch (error) {
        console.error('服务器启动失败:', error);
        process.exit(1);
    }
}

// 启动服务器
startServer(); 